<template>
    <div>
        <div class="nav_bar">
            <van-nav-bar 
                title="用户注册"
                left-text="返回"
                left-arrow
                @click-left="goBack"
            />
        </div>
        <div class="form_bar">
            <van-field
                v-model="username"
                placeholder="请输入用户名"
                label="用户名"
                icon="clear"
                @click-icon="username=''"
                required
                :error-message="usernameErrorMsg"
            />
            <van-field
                v-model="password"
                type="password"
                label="密码"
                placeholder="请输入密码"
                required
                :error-message="passwordErrorMsg"
            />
            <van-button type="primary" size="large" :loading="openLoading" @click="registerAction()">立即注册</van-button>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
import url from '@/serviceAPI.confing.js'

import { Toast } from 'vant';
export default {
    data(){
        return{
            username:"",
            password:"",
            openLoading:false, //是否开启用户的Loading
            usernameErrorMsg : '' , //当用户名出现错误时
            passwordErrorMsg : '' , //当密码出现错误时
        }
    },
    methods:{
        goBack(){
            this.$router.go(-1)
        },
        //提交注册信息，并且向后台发送请求
        axiosRegisterUser(){
            this.openLoading = true
            axios({
                url: url.registerUser,
                method: 'post',
                data:{
                    userName:this.username,
                    password:this.password ,
                }
            })
            .then(response => {
                console.log(response)
                if(response.data.code==200){
                    Toast.success('注册成功');
                    this.$router.push('/')
                }else{
                    Toast.fail('注册失败');
                    this.openLoading = false
                }
            })
            .catch((error) => {
                console.log(error)
                Toast.fail('注册失败');
                this.openLoading = false
            })
        },
        checkForm(){
            let isOk = true
            if(this.username.length<5){
                this.usernameErrorMsg = '用户名不能少于5位'
                isOk = false
            }else{
                this.usernameErrorMsg = ''
            }
            if(this.password.length<6){
                this.passwordErrorMsg = '密码不能少于6位'
            }else{
                this.passwordErrorMsg = ''
            }
            return isOk
        },
        registerAction(){
            this.checkForm() && this.axiosRegisterUser()
        }
    }
}
</script>

<style scoped>
.form_bar{
    padding:1rem 2rem;
    background: #FFF;
}
.van-cell{
    margin-bottom:1rem;
}
</style>